package com.sale.salesystem.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sale.salesystem.entity.DashboardPermission;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface DashboardPermissionMapper extends BaseMapper<DashboardPermission> {
    
    @Select("SELECT * FROM dashboard_permission WHERE dashboard_id = #{dashboardId}")
    List<DashboardPermission> selectByDashboardId(@Param("dashboardId") Long dashboardId);
    
    @Select("SELECT * FROM dashboard_permission WHERE visitor_id = #{visitorId}")
    List<DashboardPermission> selectByVisitorId(@Param("visitorId") Long visitorId);
    
    @Select("SELECT COUNT(*) > 0 FROM dashboard_permission WHERE dashboard_id = #{dashboardId} AND visitor_id = #{visitorId}")
    boolean existsByDashboardIdAndVisitorId(
        @Param("dashboardId") Long dashboardId, 
        @Param("visitorId") Long visitorId
    );
    
    @Delete("DELETE FROM dashboard_permission WHERE dashboard_id = #{dashboardId} AND visitor_id = #{visitorId}")
    void deleteByDashboardIdAndVisitorId(
        @Param("dashboardId") Long dashboardId, 
        @Param("visitorId") Long visitorId
    );

    @Select("SELECT COUNT(*) > 0 FROM dashboard_permission dp " +
            "JOIN dashboard_info di ON dp.dashboard_id = di.id " +
            "WHERE dp.visitor_id = #{userId} AND di.type = #{dashboardType}")
    boolean existsByVisitorIdAndDashboardType(
        @Param("userId") Long userId, 
        @Param("dashboardType") String dashboardType
    );

    @Select("SELECT DISTINCT di.type FROM dashboard_permission dp " +
            "JOIN dashboard_info di ON dp.dashboard_id = di.id " +
            "WHERE dp.visitor_id = #{userId}")
    List<String> selectAccessibleTypesByUserId(@Param("userId") Long userId);

    /**
     * 批量插入权限
     * @param permissions 权限列表
     * @return 插入的记录数
     */
    int batchInsert(List<DashboardPermission> permissions);
}